$(function () {
    var $form = $("form");
    var validate = $form.validate();

    /**
     * 注册
     */
    function register() {
        $("#submit").off("click").addClass("disabled").html("<span class='fa fa-pulse fa-spinner'></span>正在提交");
        if (validate.form()) {
            var url = $form.attr("action");
            $.post(url, $form.serialize(), function (data) {
                if (data['code'] && data['code'] !== '0') { // 注册失败
                    if (data['code'] === "1005") {
                        $("#email").closest(".form-group").removeClass("has-success").addClass('has-error');
                    }
                    var errorAlertHtml = [];
                    errorAlertHtml.push('<div class="alert alert-danger alert-dismissible fade in" role="alert">');
                    errorAlertHtml.push('  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button>');
                    errorAlertHtml.push('  <span>' + data['msg'] + '</span>');
                    errorAlertHtml.push('</div>');
                    $form.find("div.alert").remove();
                    $form.prepend($(errorAlertHtml.join("")));
                    $("#submit").on("click", register).removeClass("disabled").html("提交");
                } else { // 注册成功
                    $("#submit").html("注册成功,正在跳转...");
                    window.setTimeout(function () {
                        window.location.href = NOTE_PAGE;
                    }, 1000);
                }
            });
        } else {
            $("#submit").on("click", register).removeClass("disabled").html("提交");
        }
    }

    $("#submit").on("click", register);
    $("#reset").on("click", function () {
        $form.find(".form-group").removeClass("has-error").removeClass("has-success").find(".help-block").remove();
        $form.find("div.alert").remove();
    });
    $("#cancel").on("click", function () {
        history.go(-1);
    });
});
